/**
 * 作者：伍祖清
 * 时间：2016-03-22 微信端
 * 描述：ajax统一请求和获取连接参数工具类
 */
var base = null;
window.app = {};
var cache = {};
var httpHead = window.location.href.split(':')[0];
var server_host = httpHead+'://xindian.jmodata.com/wlyPhone/api/';
//var server_host = httpHead+'://192.168.0.63:6780/phone/api/';
var server_root = httpHead+'://wx.xinmailuo.com/';
//var server_root = httpHead+'://test.gyyxjqd.com/';
var storege = window.localStorage;
var HISTORY = "app_history";
var TRANS_PARAM = "tans_param";
base = base || {
	/**
	 * URL管理
	 */
	url: {
		loginWxUser:server_host+'loginWxUser',//	登录
		getHomePageData:server_host+'getHomePageData',//	首页数据
		searchResult:server_host+'searchResult',//	首页数据
		getSearchData:server_host+'getSearchData',//搜索记录
		getGoodsInfo:server_host+'getGoodsInfo',//商品详情
		addPraiseLog:server_host+'addPraiseLog',//添加点赞记录
		delPraiseLog:server_host+'delPraiseLog',//取消点赞
		addShareLog:server_host+'addShareLog',//添加分享记录
		pushingGoods:server_host+'pushingGoods',//小U推荐
		getMySpecialList:server_host+'getMySpecialList',//我的专场
		getEvaluateGoodsList:server_host+'getEvaluateGoodsList',//获取商品评价列表
		evaluateGoods:server_host+'evaluateGoods',//商品评价
		getGoodsMark:server_host+'getGoodsMark',//获取商品印记信息
		getOrderList:server_host+'getOrderList',//获取订单列表
		placeOrder:server_host+'placeOrder',//下订单
		delAddress:server_host+'delAddress',//删除收货地址
		getAddressInfo:server_host+'getAddressInfo',//获取收货地址详情
		setDefaultAddress:server_host+'setDefaultAddress',//设置默认收货地址
		getAddressList:server_host+'getAddressList',//获取收货地址列表
		saveAddress:server_host+'saveAddress',//保存收货地址
		delCollection:server_host+'delCollection',//删除收藏
		getCollectionList:server_host+'getCollectionList',//获取收藏
		addCollection:server_host+'addCollection',//添加收藏
		delShoppingCart:server_host+'delShoppingCart',//删除购物车
		getShoppingCart:server_host+'getShoppingCart',//获取购物车
		addShoppingCart:server_host+'addShoppingCart',//加入购物车
		getStandard:server_host+'getStandard',//商品规格
		goodsListByBoutique:server_host+'goodsListByBoutique',//精品分类商品列表
		goodsListByType:server_host+'goodsListByType',//普通分类商品列表
		uploadFile:server_host+'uploadFile',//文件上传
		updatePersonalInfo:server_host+'updatePersonalInfo',//修改用户信息
		getPersonalInfo:server_host+'getPersonalInfo',//获取个人信息
		myCenter:server_host+'myCenter',//个人中心
		bindingUser:server_host+'bindingUser',//绑定用户号码
		sendVerificationCode:server_host+'sendVerificationCode',//发送验证码
		storeList:server_host+'storeList',//门店列表（门店选择）
		technicianList:server_host+'technicianList',//技术员列表（技术员选择）
		technicianEvaluateList:server_host+'technicianEvaluateList',//技术员评价列表
		chooseStoreAndTechnician:server_host+'chooseStoreAndTechnician',//选择门店及技术员
		deleteOrder:server_host+'deleteOrder',//删除订单
		cancelOrder:server_host+'cancelOrder',//取消订单
		confirmOder:server_host+'confirmOder',//确认收货
		perpay:server_host+'perpay',//生成微信预付单
		getGoodsType:server_host+'getGoodsType',//获取商品类型 
		getMerchantGoods:server_host+'getMerchantGoods',//获取商家商品
		getSeckillGoodsList:server_host + 'getSeckillGoodsList',//获取秒杀商品
		buySeckillGooods: server_host + 'buySeckillGooods',//特价商品下单
	},
	/**
	 * ajax请求
	 * @param {Object} url请求连接
	 * @param {Object} data请求参数
	 * @param {Object} callback回调函数
	 */
	postData : function(url, data, callback) {
		console.log(url+"?"+JSON.stringify(data));
		$.ajax({  
            type: "post", //HTTP请求类型 
            url: url,  
            data: data,  
            dataType: 'json', //服务器返回json格式数据
            timeout:20000,//超时时间设置为20秒；
            success: function (data) {
            		console.log(data);
            		callback(data);
            }, //服务器返回响应
            error: function (xhr,type,errorThrown) {  
                //异常处理；
				console.log(type);
				if(this.spinner != null && this.spinner != ''){
					base.clearWait();
				}
				if(xhr.status==200){
					var errorstr = xhr.responseText;
//					var data = JSON.parse(errorstr);  
					var data = eval('(' + errorstr + ')');
					callback(data);
				}else{
//					mui.toast("请求出错！");	
				}
            }  
        });
	},
	/**
	 * 获取URL链接参数，在通过URL跳转页面时，可通过此方法获取URL的参数
	 * @param {Object} val要获取的参数名称
	 */
	getParameter : function(val){
		var uri = window.location.search;
		var re = new RegExp("" + val + "=([^&?]*)", "ig");
		var str = ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 1)) : null);
		return decodeURIComponent(str);
	},
	getSavedData: function() {
		var history = JSON.parse(storege[HISTORY] || '[]');
		var item = history[history.length - 1];
		if (!item) {
			console.log('save:', {});
			return {};
		}
		var path = window.location.pathname;
		if (item.path == path) {
			history.pop();
			storege[HISTORY] = JSON.stringify(history);
			scrollTop = item.scrollTop;
			this.from = item.from;
			this.isBack = true;
			console.log('save:', item.saved || {});
			return item.saved || {};
		} else {
			this.from = item.path;
			this.isBack = false;
			console.log('save:', item.saved || {});
			return {};
		}
	},
	showView: function(url, param, saved, getScrollTop) {
		scrollTop = undefined;
		var history = JSON.parse(storege[HISTORY] || '[]');
		history.push({
			href: window.location.href,
			path: window.location.pathname,
			saved: saved,
			scrollTop: getScrollTop ? getScrollTop() : $(document.body).scrollTop(),
			from: getAbsolutePath(url, window.location.pathname),
		});
		storege[HISTORY] = JSON.stringify(history);
		storege[TRANS_PARAM] = JSON.stringify(param||{});
		window.location.href = url;
	},
	/**
	 * 设置等待加载
	 * @param {Object} text
	 */
	setWait: function(text) {
        var opts = {
            lines: 12, // 花瓣数目
            length: 10, // 花瓣长度
            width: 3, // 花瓣宽度
            radius: 10, // 花瓣距中心半径
            corners: 1, // 花瓣圆滑度 (0-1)
            rotate: 0, // 花瓣旋转角度
            direction: 1, // 花瓣旋转方向 1: 顺时针, -1: 逆时针
            color: '#FBDC9F', // 花瓣颜色
            speed: 1, // 花瓣旋转速度
            trail: 60, // 花瓣旋转时的拖影(百分比)
            shadow: false, // 花瓣是否显示阴影
            hwaccel: false, //spinner 是否启用硬件加速及高速旋转
            className: 'spinner', // spinner css 样式名称
            zIndex: 2e9, // spinner的z轴 (默认是2000000000)
    //      top: 'auto', // spinner 相对父容器Top定位 单位 px
    //      left: 'auto'// spinner 相对父容器Left定位 单位 px
        };
    	this.spinner = new Spinner(opts);
        $(document.body).append('<div id="mask_container"><div class="modal-backdrop"></div><div class="spinner-text-container">'+text+'</div></div>');
    	this.spinner.spin(document.body);//打开等待加载
    },
    clearWait: function() {
        $("#mask_container").remove();
        if (this.spinner != null) {
        	this.spinner.spin();//关闭等待加载	
        }
        this.spinner = null;
    },
    /**
	 * 是否是微信浏览器
	 */
	isOnWx: function() {
		var ua = window.navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i) == 'micromessenger'){
            return true;
        } else {
            return false;
        }
	},
    /**
	 * 初始化配置
	 * @param onReady 初始化成功后的回调
	 */
	initWX: function(onReady) {
		//避免重复调用
		if(cache.wxInited) {
			return;
		}
		cache.wxInited = true;

		if(!base.isOnWx()) {
			console.info("please debug this page on weixin browser.");
			return;
		}
		
//		var url = encodeURIComponent(location.href);
		var url = window.location.href;
		base.postData(server_root+'js.wx/wx/getJsApiCfgByH5.do',{url: url},function(res){
			var data = res.data;
			wx.config({
				debug: false,
				appId : data.appId,
				timestamp: data.timestamp, //生成签名的时间戳
				nonceStr: data.nonceStr, //生成签名的随机串
				signature: data.signature,//签名
				jsApiList: ['hideMenuItems', 'getLocation', 'openLocation', 'chooseWXPay', 'chooseImage', 'previewImage', 'uploadImage','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone','closeWindow'] //需要使用的JS接口列表
			});
		});

		wx.ready(function(){
			//mui.toast("微信初始化成功！");
			if(onReady != null) {
				onReady();
			}
			//批量隐藏功能
//		    wx.hideMenuItems({
//		        menuList: ['menuItem:copyUrl'] // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
//		    });
		});

		wx.error(function(res){
			mui.toast("微信初始化失败！");
		});
	},
	/**
	 * 统一绑定分享按钮事件
	 */
	bindShare: function(shareData) {
		shareData.success = shareData.success|| function () { // 用户确认分享后执行的回调函数
			//do noting
			mui.toast('success');
		},
		shareData.cancel = shareData.cancel||function () { // 用户取消分享后执行的回调函数
			//do noting
			mui.toast('cancel');
		}
		wx.onMenuShareTimeline(shareData);//朋友圈
		wx.onMenuShareAppMessage(shareData);//微信好友
		wx.onMenuShareQQ(shareData);//qq
		wx.onMenuShareWeibo(shareData);//微博
		wx.onMenuShareQZone(shareData);//qq空间
		 
		//隐藏一些没什么用的按钮		
 

	},
	/**
	 * 微信支付
	 */
	weChatPay: function(orderNo, userID, onSuccess, onCancel, onFail) {
		if(!base.isOnWx()) {
			mui.toast("请在微信端调用此功能");
			return;
		}
		base.setWait('正在加载...');
		base.postData(base.url.perpay, {orderNo: orderNo, userID: userID}, function(res){//下微信预付单
			base.clearWait();
			if (res.success) {
				onSuccess(res.obj);
			}
//			var cfg = res.obj;
			//weui.dialog(JSON.stringify(cfg));
//			wx.chooseWXPay({
//				timestamp: cfg.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
//				nonceStr: cfg.nonceStr, // 支付签名随机串，不长于 32 位
//				package: cfg.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
//				signType: cfg.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
//				paySign: cfg.sign, // 支付签名
//				success: function (res) {
//					base.clearWait();
//					if(onSuccess) {
//						onSuccess(res);
//					}
//				},
//				cancel: function(res) {
//					base.clearWait();
//					//mui.toast("支付被取消");
//					if(onCancel) {
//						onCancel();
//					}
//				},
//				fail: function(res, arg2) {
//					base.clearWait();
//					mui.toast("对不起，支付失败:"+JSON.stringify(res)+","+JSON.stringify(arg2));
//					if(onFail) {
//						onFail();
//					}
//				}
//			});
		});
	},
    
}

app.global = (function() {
	var ls = window.localStorage;
	var GLOBAL = "app_global";
	var global = {
		set: function(key, data) {
			var global = JSON.parse(ls[GLOBAL] || '{}');
			global[key] = data;
			ls[GLOBAL] = JSON.stringify(global);
		},
		add: function(key, data) {
			var global = JSON.parse(ls[GLOBAL] || '{}');
			global[key].push(data);
			ls[GLOBAL] = JSON.stringify(global);
		},
		get: function(key) {
			var global = JSON.parse(ls[GLOBAL] || '{}');
			return global[key];
		},
		getOnce: function(key) {
			var global = JSON.parse(ls[GLOBAL] || '{}');
			var ret = global[key];
			if (ret != null) {
				delete global[key];
			}
			ls[GLOBAL] = JSON.stringify(global);
			return ret;
		},
		clear: function(key) {
			var global = JSON.parse(ls[GLOBAL] || '{}');
			delete global[key];
			ls[GLOBAL] = JSON.stringify(global);
		}
	};
//	console.log('global:', ls[GLOBAL]);
	return global;
})();

function getAbsolutePath(from, path) {
	if (from[0] === '/') {
		return from;
	}
	var parr = path.split('/').slice(0, -1);
	var farr = from.split('/');
	for (var i in farr) {
		var item = farr[i];
		if (item === '.') {
			continue;
		} else if (item === '..') {
			parr.pop();
		} else {
			parr.push(item);
		}
	}
	return parr.join('/');
}
